package com.roger.uia.helper.util;

import android.content.Context;
import android.os.Build;
import android.os.storage.StorageManager;
import android.support.test.InstrumentationRegistry;
import android.util.Log;

import com.roger.uia.helper.UiBase;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

import static com.roger.uia.helper.UiBase.mDevice;

@SuppressWarnings("ResultOfMethodCallIgnored")
public class FileUtils {
    private static final String TAG = "Test" + FileUtils.class.getSimpleName();

    public static void getPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                mDevice.executeShellCommand("pm grant " + InstrumentationRegistry.getTargetContext().getPackageName() + " android.permission.READ_EXTERNAL_STORAGE");
                mDevice.executeShellCommand("pm grant " + InstrumentationRegistry.getTargetContext().getPackageName() + " android.permission.WRITE_EXTERNAL_STORAGE");
            } catch (IOException e) {
                Log.d(TAG,"grant permission fail");
            }
        }
    }


    public static void createFolder(File folder){
        if (!folder.exists()) folder.mkdirs();
    }

    public static void delFolder(File folder) {
        if (folder.isDirectory()) {
            String[] files = folder.list();
            for (String file : files) {
                delFolder(new File(folder, file));
            }
        }
        folder.delete();
    }

    public static void takeScreenPicTo(String filePath, String picName) {
        try {
            File fp = new File(filePath);
            if (!fp.exists()) mDevice.executeShellCommand("mkdir -p " + fp);
            Date curDate = new Date(System.currentTimeMillis());
            String time = UiBase.dateFormat.format(curDate);
            File pic = new File(fp + "/" + picName+"_"+time+ ".png");
            mDevice.executeShellCommand("screencap -p " + pic);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static boolean existFile(String file){
        File f = new File(file);
        return f.exists();
    }

    public static void deleteFile(String file){
        File f = new File(file);
        if(f.exists()) f.delete();
    }

    public static void writeFile(String file, String content){
        String strContent = content + "\n";
        try {
            File f = new File(file);
            if (!f.exists()) {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(f.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getJson(String Path,String newId){
        String string=null;
        try {
            File file = new File(Path);
            FileInputStream isr = new FileInputStream(file);
            BufferedReader bf = new BufferedReader(new InputStreamReader(isr));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            JSONObject root = new JSONObject(stringBuilder.toString());
            JSONArray array = root.getJSONArray("config");
            JSONObject params = array.getJSONObject(0);
            JSONArray paramsData = params.getJSONArray("params");
            for (int i = 0; i < paramsData.length(); i++) {
                JSONObject data = paramsData.getJSONObject(i);
                String id = data.getString("id");
                if (newId.equals(id)) {
                    string = (data.getString("value"));
                }
            }
            bf.close();
            isr.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return string;
    }

    public static int getTxtRows(String Path){
        int rows=0;
        try {
            File file = new File(Path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ( br.readLine() != null) {
                rows++;
            }
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return rows;
    }

    public static String getTxt(String Path,int row){
        String [] string = new String[0];
        try {
            File file = new File(Path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n");
            }
            string=stringBuilder.toString().split("\n");
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return string[row];
    }

    public static String readTxtS(String path){
        StringBuilder s = new StringBuilder();
        try {
            InputStream in = new FileInputStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line ="";
            while((line=br.readLine())!=null){
                s.append(line);
            }
            br.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s.toString();
    }

    public static Set<String> readTxt(String path){
        Set<String> set = new TreeSet<>();
        try {
            InputStream in = new FileInputStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line ="";
            while((line=br.readLine())!=null){
                set.add(line);
            }
            br.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return set;
    }

    @SuppressWarnings("JavaReflectionMemberAccess")
    public static String getSecondaryStoragePath(){
        try {
            StorageManager sm = (StorageManager) InstrumentationRegistry.getTargetContext().getSystemService(Context.STORAGE_SERVICE);
            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths",  null);
            String[] paths = (String[]) getVolumePathsMethod.invoke(sm,  null);
            return paths.length <= 1 ? null : paths[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
